package com.bit.bit_forum.exception;

import com.bit.bit_forum.common.AppResult;
import com.bit.bit_forum.common.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 全局异常处理
 */
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {

    @ResponseBody
//    要处理那种异常
    @ExceptionHandler(ApplicationException.class)
    public AppResult handleApplicationException(ApplicationException e){
//        打印异常信息
        e.printStackTrace();
        //打印日志
//        log.error(e.getMessage());
        if(e.getErrorResult()!=null){
            return e.getErrorResult();
        }
        if(e.getMessage()==null || e.getMessage().equals("")){
            return AppResult.failed(ResultCode.ERROR_SERVICES);
        }
        return AppResult.failed(e.getMessage());
    }

//    处理未捕获的其他异常
    @ResponseBody
    @ExceptionHandler(Exception.class)
    public AppResult handleException(Exception e){
        e.printStackTrace();
//        log.error(e.getMessage());
        if(e.getMessage()==null || e.getMessage().equals("")){
            return AppResult.failed((ResultCode.ERROR_SERVICES));
        }
        return AppResult.failed(e.getMessage());
    }

}
